window.__permissionList = undefined;

let one = sessionStorage.getItem('_onelevel');
let two = sessionStorage.getItem('_twolevel');
let three = sessionStorage.getItem('_threelevel');
let four = sessionStorage.getItem('_fourlevel');

window._onelevel = one ? JSON.parse(one) : {};
window._twolevel = two ? JSON.parse(two) : {};
window._threelevel = three ? JSON.parse(three) : {};
window._fourlevel = four ? JSON.parse(four) : {};
window.addEventListener('beforeunload', () => {
    sessionStorage.setItem('_onelevel', JSON.stringify(_onelevel))
    sessionStorage.setItem('_twolevel', JSON.stringify(_twolevel))
    sessionStorage.setItem('_threelevel', JSON.stringify(_threelevel))
    sessionStorage.setItem('_fourlevel', JSON.stringify(_fourlevel))
})

function isEmpty(data) {
    if (Object.keys(data).length === 0) {
        return true;
    } else {
        return false;
    } 
}


export default {
    bind: function (el, binding, vnode) {
        //解构获取context，借此访问Vuex的store
        const { context: vm } = vnode;
        if (!__permissionList) {
            __permissionList = vm.$store.getters['roleInfo/getUserPermissions'];
        }
        //如果sessionStorage 没有存储用户权限信息 遍历各级权限，并加入各级权限对象
        if (isEmpty(_onelevel) && isEmpty(_twolevel) && isEmpty(_threelevel) && isEmpty(_fourlevel)) {
            __permissionList.forEach(one => {
                _onelevel[one.name] = true;
                if (one.childPermission.length > 0) {
                    one.childPermission.forEach(two => {
                        _twolevel[two.name] = true;
                        if (two.childPermission.length > 0) {
                            two.childPermission.forEach(three => {
                                _threelevel[three.name] = true;
                                if (three.childPermission.length > 0) {
                                    three.childPermission.forEach(four => {
                                        _fourlevel[four.name] = true;
                                    })
                                }
                            })
                        }
                    })
                }
            })
        }
        if (_onelevel[binding.value] || _twolevel[binding.value] || _threelevel[binding.value] || _fourlevel[binding.value]) {
            //存在则可点击
            // console.log(binding.value + '存在');
            el.disabled = false;
            el.classList.remove("is-disabled");
            return;
        }
        // console.log(binding.value + '不存在');
        if (el.className === 'el-menu-item' || el.className === 'el-submenu') {
            // 如果是导航栏且不具备权限直接隐藏
            el.style.display = 'none';
            return
        }
        el.disabled = true;
        el.classList.add("is-disabled")
    }
}


